package com.topnav.mc.admin.security.jwt.handle;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.js.lib.cache.Cache;
import com.js.lib.cache.SysCache;
import com.js.lib.result.Result;
import com.topnav.mc.admin.entity.*;
import com.topnav.mc.admin.entity.enums.EnumLogType;
import com.topnav.mc.admin.entity.enums.EnumOperateFunction;
import com.topnav.mc.admin.security.CustomLoginSuccess;
import com.topnav.mc.admin.security.PermissionGrade;
import com.topnav.mc.admin.security.jwt.utils.JwtTokenUtil;
import com.topnav.mc.admin.service.*;
import com.topnav.mc.common.Constant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;


/**
 * 说明： 自定义登录成功处理器
 * @类名: Role
 * <p>
 *
 * </p>
 * @author   kenny
 * @Date	 2022年2月9日下午5:26:18
 */
@Component
@Slf4j
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
/*    @Autowired
    private IUserService userService;
    @Autowired
    private IOrganizationService organizationService;
    @Autowired
    private IUserOrganizaitonService userOrganizaitonService;
    @Autowired
    private IRoleService roleService;
    @Autowired
    private SysCache sysCache;*/
    @Resource
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private CustomLoginSuccess customLoginSuccess;



    @Override
    public void onAuthenticationSuccess(
    		HttpServletRequest httpServletRequest,
    		HttpServletResponse httpServletResponse,
    		Authentication authentication) throws IOException, ServletException {



        log.info("Session:{}",httpServletRequest.getSession().getId());

        String ip= httpServletRequest.getHeader("X-FORWARDED-FOR");
        if (ip == null || "".equals(ip)) {
            ip = httpServletRequest.getRemoteAddr();
        }

        //log.info(">>>>>>>>>>>>>>>>>>>> client_ip: {}",ip);

        /** 生成token, 并返回前端 */
        final String realToken = jwtTokenUtil.generateToken(authentication.getName(),ip);

        /** 将生成的authentication放入容器中，生成安全的上下文 */
        SecurityContextHolder.getContext().setAuthentication(authentication);

        HashMap<String,Object> map = new HashMap<>();
        map.put("token", realToken);
        map.put("loginName", authentication.getName());
        /** 返回登录用户的附加信息 */
        Object obj = customLoginSuccess.afterLoginSuccess(authentication.getName(),realToken);
        map.put("userInfo",obj);

        if (log.isDebugEnabled()){
            log.debug("[{}] 登录成功",authentication.getName());
        }
        String json =  JSON.toJSONString(Result.ok("登录成功",map));
        // 允许跨域
        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
        // 允许自定义请求头token(允许head跨域)
        httpServletResponse.setHeader("Access-Control-Allow-Headers", "token, Accept, Origin, X-Requested-With, Content-Type, Last-Modified");
        httpServletResponse.setContentType("text/json;charset=utf-8");
        httpServletResponse.getWriter().write(json);

    }


}
